import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:finance_app/src/widgets/select/normal_radio.dart';
import 'package:flutter/material.dart';

class AddDiscountForm extends StatefulWidget {
  final TextEditingController controller;
  final FocusNode focusNode;
  final bool isCheckPercentage;
  final ValueChanged<bool> onChange;
  const AddDiscountForm(
      {Key key,
      @required this.isCheckPercentage,
      @required this.controller,
      @required this.focusNode,
      this.onChange})
      : super(key: key);

  @override
  _AddDiscountFormState createState() => _AddDiscountFormState();
}

class _AddDiscountFormState extends State<AddDiscountForm> {
  bool isCheckPercentage;

  @override
  void initState() {
    isCheckPercentage = widget.isCheckPercentage ?? false;
    if (widget.controller.text == 'null') {
      widget.controller.clear();
    }
    super.initState();
  }

  void _onChangePercentage(bool value) {
    setState(() {
      if (value == isCheckPercentage) return;
      isCheckPercentage = value;
      widget.controller.clear();
      if (widget.onChange != null) {
        widget.onChange(isCheckPercentage);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            AppSpaces.w35,
            PressedOpacityButton(
              onPressed: () => _onChangePercentage(false),
              child: NormalRadio(
                title: S.current.flat_amount,
                isSelect: !isCheckPercentage,
              ),
            ),
            AppSpaces.w35,
            PressedOpacityButton(
              onPressed: () => _onChangePercentage(true),
              child: NormalRadio(
                title: S.current.percentage,
                isSelect: isCheckPercentage,
              ),
            ),
          ],
        ),
        AppSpaces.h20,
        AppSpaces.grayH05,
        FromInputField(
          tip: '${S.current.discount}${isCheckPercentage == true ? '(%)' : ''}',
          controller: widget.controller,
          focusNode: widget.focusNode,
          inputFormatterList: [
            if (isCheckPercentage)
              percentInputFormatter4
            else
              doubleLimit2InputFormatter
          ],
        ),
      ],
    );
  }
}
